package com.jean.business.admin.controller;

import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.jean.business.event.resp.BaseResp;
import com.jean.business.event.resp.SimpleResp;
import com.jean.business.RespFactory;
import com.jean.business.admin.AdminSessionManage;
import com.jean.business.bean.AdminInfo;
import com.jean.common.ConstantConfigs;
import com.jean.common.ConstantReturnCode;
import com.jean.init.MusicContext;
import com.jean.util.EncryptTool;
import com.jean.util.LoggerFactory;

/**
 * <一句话功能简述>管理员请求Controller层 <功能详细描述>
 * 
 * @author Jean
 * @version [版本号, 2013年12月4日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@RequestMapping(ConstantConfigs.REQUEST_MODULE_ADMIN)
public class AdminAccountManageController
{
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger();
    
    /**
     * 是否刷新session标识
     */
    private static boolean ADMIN_REFRESH_SESSION_FLAG = false;
    
    /**
     * <一句话功能简述>管理员登录接口 <功能详细描述>
     * 
     * @param request 请求
     * @param account 账号
     * @param password 密码
     * @return 登录结果
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/signin")
    @ResponseBody
    public BaseResp signIn(HttpServletRequest request,
        HttpServletResponse response, AdminInfo admin)
    {
        logger.info("admin sign in control start...");
        BaseResp resp = new BaseResp();
        if (StringUtils.isEmpty(admin.getAccount())
            || StringUtils.isEmpty(admin.getPassword()))
        {
            logger.warn("admin sign in  fail, the mandatory parameter is empty. account: "
                + admin.getAccount());
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_PARAMETER_EMPTY);
            return resp;
        }
        
        SqlMapClient sqlMapClient = MusicContext.getSqlMapClient();
        AdminInfo adminInfo = new AdminInfo();
        try
        {
            adminInfo =
                (AdminInfo)sqlMapClient.queryForObject("queryAdminByAccount",
                    admin.getAccount());
        }
        catch (SQLException e)
        {
            logger.error("SqlMapClient queryAdminByAccount error", e);
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_DATABASE_ABNORMAL);
            return resp;
        }
        if (StringUtils.isEmpty(adminInfo.getPassword()))
        {
            logger.warn("the password in database is null, account: "
                + admin.getAccount());
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_LOGIN_FAIL);
            return resp;
        }
        if (!adminInfo.getPassword()
            .equals(EncryptTool.encrypt(admin.getPassword())))
        {
            resp =
                RespFactory.getResp(request,
                    ConstantReturnCode.MUSIC_ACCOUNT_PWD_NOT_CORRECT);
            return resp;
        }
        
        // 登录成功，将admin账号信息存入session
        request.getSession()
            .setAttribute(ConstantConfigs.SESSION_ADMIN_ACCOUNT, adminInfo);
        
        // 解決https跳转http，session失效的问题
        Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());
        response.addCookie(cookie);
        
        // 下次第一次调用checklogin时，刷新session
        ADMIN_REFRESH_SESSION_FLAG = true;
        resp = RespFactory.getResp(request, ConstantReturnCode.MUSIC_SUCCESS);
        return resp;
    }
    
    @RequestMapping("/adminchecklogin")
    @ResponseBody
    public BaseResp adminCheckLogin(HttpServletRequest request,
        HttpServletResponse response)
    {
        logger.info("admin check login control start...");
        SimpleResp<Object> resp = new SimpleResp<Object>();
        
        // 判断是否刷新session
        if (ADMIN_REFRESH_SESSION_FLAG)
        {
            AdminSessionManage.refreshSession(request);
        }
        
        if (!AdminSessionManage.isAdminOnline(request))
        {
            resp.setResultInfo(RespFactory.getResultInfo(request,
                ConstantReturnCode.MUSIC_SESSION_NULL));
            return resp;
        }
        resp.setRecord(request.getSession()
            .getAttribute(ConstantConfigs.SESSION_ADMIN_ACCOUNT));
        resp.setResultInfo(RespFactory.getResultInfo(request,
            ConstantReturnCode.MUSIC_SUCCESS));
        return resp;
    }
}
